<?php
/**
 * @author     ：lhw
 * @date       ：Created in 2019/8/4 19:15
 */

namespace app\api\service;

use app\api\model\Drug as DrugModel;
use app\api\model\OrderMaster as OrderMasterModel;
use app\api\model\OrderDetail as OrderDetailModel;
use app\exception\OrderExceptions;
use think\Db;
use think\Exception;

class UserOrderService extends BaseService
{
    public static function create($useris_id,$useris_address,$useris_phone,$hdfk,$items){
        Db::startTrans();
        try{
            $details = [];
            $all_price = 0.0;
            $father_pharmacy = 0;
            //计算总价  计算父企业
            if(is_array($items)){
                foreach ($items as $item){
                    if(array_key_exists('drug_id',$item) && array_key_exists('num',$item)){
                        $drug = DrugModel::where(['id' => $item['drug_id']])->find();

                        array_push($details,[
                            'drug_id' => $drug->id,
                            'price' => $drug->price,
                            'num' => $item['num']
                        ]);

                        $all_price += $drug->price * $item['num'];

                        if($father_pharmacy == 0)
                            $father_pharmacy = $drug->father_pharmacy;
                        if($father_pharmacy != $drug->father_pharmacy)
                            throw new OrderExceptions();
                    }
                }
            }

            $master = OrderMasterModel::create([
                'useris_id' => $useris_id,
                'useris_address' => $useris_address,
                'useris_phone' => $useris_phone,
                'all_price' => $all_price,
                'father_pharmacy' => $father_pharmacy,
                'hdfk' => $hdfk
            ]);

            $id = $master->id;

            foreach ($details as $detail) {
                OrderDetailModel::create([
                    'order_id' => $id,
                    'drug_id' => $detail['drug_id'],
                    'price' => $detail['price'],
                    'num' => $detail['num']
                ]);
            }

            return $id;
        }catch (Exception $e){
            Db::rollback();
            throw $e;
        }finally{
            Db::commit();
        }

    }


}